package br.srv.full.faces.postalservices.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import br.srv.full.geoProcessing.entities.GPSPoint;

public class LatitudeLongitudeConverter implements Converter {

	/**
	 * 
	 */
	private static final GPSPoint GPSPOINT = new GPSPoint(0, 0);
	private final Log log = LogFactory.getLog(getClass());

	public LatitudeLongitudeConverter() {
		log.info("Inicializado");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext,
	 *      javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext p_context, UIComponent p_component, String p_value) {
		// TODO Auto-generated method stub

		log.info("getAsObject: " + p_value);
		String l_value = p_value.replace('(', ' ').replace(')', ' ');
		if (p_value == null || p_value.isEmpty() || l_value.replace(',', ' ').isEmpty())
			return GPSPOINT;
		else {
			String[] l_split = l_value.split("\\((d*?),(d*?)\\)");
			if (l_split.length < 2)
				return GPSPOINT;
			String latitude = l_split[0];
			String longitude = l_split[1];
			return new GPSPoint(Float.parseFloat(latitude), Float.parseFloat(longitude));
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext,
	 *      javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext p_context, UIComponent p_component, Object p_value) {
		log.info("getAsString: " + p_value);
		if (p_value instanceof GPSPoint) {
			GPSPoint l_value = (GPSPoint) p_value;

			return "(" + l_value.getLatitude() + ", " + l_value.getLongitude() + ")";
		} else
			return p_value.toString();
	}

}
